import { ConfigModule, ConfigService } from '@nestjs/config';
import { SequelizeModule } from '@nestjs/sequelize';
import { Dialect } from 'sequelize';
import { Photo } from './photo.model';
import { User } from './user.model';
import { Token } from './token.model';
import { ExampleUpgrade } from './example_upgrade.model';
import { CommandRecord } from './command_record';

export const setupModules = () => {
  return SequelizeModule.forRootAsync({
    imports: [ConfigModule],
    inject: [ConfigService],
    useFactory(configService: ConfigService) {
      const database = {
        host: configService.get<string>('DATABASE_HOST'),
        port: configService.get<number>('DATABASE_PORT'),
        username: configService.get<string>('DATABASE_USER'),
        password: configService.get<string>('DATABASE_PASSWORD'),
        database: configService.get<string>('DATABASE_DATABASE')
      };
      return {
        dialect: configService.get<Dialect>('DATABASE_TYPE'),
        replication: {
          write: database,
          read: [database]
        },
        autoLoadModels: true,
        synchronize: true,
        timezone: '+08:00',
        benchmark: true,
        pool: {
          // 连接池设置
          max: 200, // 最大连接数
          min: 0, // 最小连接数
          idle: 1000
        },
        logging(sql, timing) {
          console.log(timing, sql);
        },
        define: {
          scopes: {
            bh: {
              attributes: { exclude: ['id', 'deletedAt'] }
            }
          },
          getterMethods: {
            createdAt() {
              const value = this.getDataValue('createdAt');
              return value && +value;
            },
            updatedAt() {
              const value = this.getDataValue('updatedAt');
              return value && +value;
            },
            deletedAt() {
              const value = this.getDataValue('deletedAt');
              return value && +value;
            }
          }
        },
        models: [User, Token, Photo, ExampleUpgrade, CommandRecord]
      };
    }
  });
};
